package com.imc.platform.base.user.security;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.log.Log;
import com.twp.common.tuple.ResultDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
*类描述：api接口过滤器
*开发者：QY
*创建时间：2018/9/14 16:14
**/

//@Component
public class ApiSecurityFilter implements Filter {

FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         config=filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hrequest = (HttpServletRequest)request;
        HttpServletResponse hresponse=(HttpServletResponse)response;
        //获取配置中对哪些请求开头做过滤
        String urlPatterns = config.getInitParameter("reqHander");
        String noFilterUrlPattern=config.getInitParameter("noFilter");
        ResultDTO resultDTO=new ResultDTO();
        //不走过滤器得请求
        if(hrequest.getRequestURI().indexOf(noFilterUrlPattern) !=-1){
            chain.doFilter(request,response);
            return;
        }else{
            //如果请求url中没有过滤中,走出过滤
            if(hrequest.getRequestURI().indexOf(urlPatterns) !=-1){
                if(hrequest.getSession().getAttribute("wxData")!=null){
                    chain.doFilter(request,response);
                    return;
                }
                hresponse.setContentType("application/json;charset=UTF-8");
                resultDTO.setIsSuccess(false);
                resultDTO.setMessage("请求失败，请确认请求参数");
                hresponse.getWriter().print(JSON.toJSONString(resultDTO));
                return;
            }else {
                chain.doFilter(request,response);
                return;
            }
        }
    }

    @Override
    public void destroy() {
          this.config=null;
    }
}
